package com.zlm.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlm.common.constant.ProductConstant;
import com.zlm.common.to.SkuReductionTo;
import com.zlm.common.to.SpuBoundTo;
import com.zlm.common.to.es.SkuEsModel;
import com.zlm.common.utils.PageUtils;
import com.zlm.common.utils.Query;
import com.zlm.common.utils.R;
import com.zlm.common.vo.SkuHasStockVo;
import com.zlm.mall.product.dao.SpuInfoDao;
import com.zlm.mall.product.entity.*;
import com.zlm.mall.product.feign.CouponFeignService;
import com.zlm.mall.product.feign.SearchFeignService;
import com.zlm.mall.product.feign.WareFeignService;
import com.zlm.mall.product.service.*;
import com.zlm.mall.product.vo.spu.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private AttrService attrService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private BrandService brandService;
    @Resource
    CategoryService categoryService;
    @Resource
    WareFeignService wareFeignService;
    @Resource
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {

        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        //2. 保存spu描述 pms_spu_info_desc
        List<String> decripts = spuSaveVo.getDecript();
        Long spuId = spuInfoEntity.getId();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",",decripts));

        spuInfoDescService.save(spuInfoDescEntity);
        //3. 保存spu图片集 pms_spu_images

        List<String> images = spuSaveVo.getImages();
        //有图片才保存
        if (images != null && images.size() > 0) {
            List<SpuImagesEntity> spuImagesEntities = images.stream().map(item -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setId(spuId);
                spuImagesEntity.setImgUrl(item);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(spuImagesEntities);
        }

        //4. 保存spu规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(item.getAttrId());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setSpuId(spuId);
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        //5.保存spu对应的sku信息
        //5.1 sku基本信息 pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        skus.forEach(item -> {
            //找出默认图片
            String defaultImage = "";
            for (Images image : item.getImages()) {
                if(image.getDefaultImg() == 1){
                    defaultImage = image.getImgUrl();
                }
            }
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(item,skuInfoEntity);
            skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());
            skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSpuId(spuId);
            skuInfoEntity.setSkuDefaultImg(defaultImage);
            skuInfoService.save(skuInfoEntity);
            //5.2 sku图片信息 pms_sku_images
            //TODO 没有图片,不需要保存
            List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setDefaultImg(img.getDefaultImg());
                skuImagesEntity.setImgUrl(img.getImgUrl());
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuImagesEntity;
            }).filter( skuImage -> {
                return StringUtils.isNotBlank(skuImage.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(imagesEntities);

            //5.3 sku销售属性值 pms_sku_sale_attr_value
            List<Attr> attrs = item.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

            //5.4 sku优惠,满减信息 mall-sms sms_aku_ladder sms_sku_full_reduction sms_member_price
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(item,skuReductionTo);
            skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
            if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) == 1) {
                R result = couponFeignService.saveSkuReduction(skuReductionTo);
                if (result.getCode() != 0) {
                    log.error("远程保存sku优惠满减信息失败");
                }
            }

        });

        //5.5 保存spu积分信息 sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }


    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String)params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(e -> {
                wrapper.eq("id",key).or()
                        .like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("publish_status",status);
        }
        Long brandId = Long.parseLong((String) params.get("brandId"));
        if (brandId !=null && brandId != 0) {
            wrapper.eq("brand_id",brandId);
        }
        Long catalogId = Long.parseLong((String) params.get("catelogId"));
        if (catalogId !=null && catalogId != 0) {
            wrapper.eq("catalog_id",catalogId);
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        //查询出当前spuId对应的所有的sku信息,品牌名称
        List<SkuInfoEntity> skuInfos = skuInfoService.getSkusBySpuId(spuId);
        //查询sku可以用来被检索的规格属性
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.baseAttrList(spuId);
        List<Long> attrIds = productAttrValueEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        //去除重复数据
        HashSet<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = productAttrValueEntities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            attr.setAttrId(item.getAttrId());
            attr.setAttrName(item.getAttrName());
            attr.setAttrValue(item.getAttrValue());
            return attr;
        }).collect(Collectors.toList());

        List<Long> skuIds = skuInfos.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> stockMap = null;
        try {
            //TODO 远程调用,查询库存
            R result = wareFeignService.getSkusHasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            stockMap = result.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, skuHasStockVo -> skuHasStockVo.getHasStock()));
        } catch (Exception e) {
            log.error("库存查询异常:原因{}",e);
            e.printStackTrace();
        }

        //封装sku数据
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> list = skuInfos.stream().map(info -> {
            //组装需要的数据
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(info, skuEsModel);
            skuEsModel.setSkuPrice(info.getPrice());
            skuEsModel.setSkuImg(info.getSkuDefaultImg());
            if (finalStockMap != null) {
                skuEsModel.setHasStock(finalStockMap.get(info.getSkuId()));
            }else{
                skuEsModel.setHasStock(true);
            }


            skuEsModel.setHasStock(false);
            //TODO 热度评分
            skuEsModel.setHotScore(0L);

            //TODO 查询品牌和分类
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            //设置检索属
            skuEsModel.setAttrs(attrsList);

            return skuEsModel;
        }).collect(Collectors.toList());

        //将数据发送给es进行保存 mall-search
        R r = searchFeignService.productStatUp(list);

        if(r.getCode() == 0){
            //远程调用成功

            //TODO 修改当前spu为上架状态
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.SpuEnum.SPU_UP.getCode());
        }else{
            //失败
            //todo 重复调用 接口幂等性 重试机制


        }


    }
}
